/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package showhistory;

import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.swing.JSpinner;
import model.*;

/**
 *
 * @author gkrik
 */
public class HistoryCollectionForm extends javax.swing.JFrame {
    /**
     * Creates new form HistoryCollectionForm
     */
    public HistoryCollectionForm() {
        em=DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }             
        initComponents();        

        //Ρύθμιση ώστε να εμφανίζονται λιγότερες λεπτομέρειες στην ημερομηνία
        //(χωρίς λεπτά, ώρες κλπ., καθώς δε μας ενδιαφέρουν)        
        jSpinnerFromDate.setEditor(new JSpinner.DateEditor(jSpinnerFromDate, "dd/MM/yyyy"));
        jSpinnerToDate.setEditor(new JSpinner.DateEditor(jSpinnerToDate, "dd/MM/yyyy"));          
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        collection = new model.Collection();
        queryHistoryCollection = em.createQuery("select c from Collection c  where c.passTimestamp>:passTimestamp order by c.passTimestamp desc").setParameter("passTimestamp", fromDate);
        listHistoryCollection = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(queryHistoryCollection.getResultList());
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jSpinnerFromDate = new javax.swing.JSpinner();
        jLabel3 = new javax.swing.JLabel();
        jSpinnerToDate = new javax.swing.JSpinner();
        jLabel4 = new javax.swing.JLabel();
        jButtonSearch = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jTextFieldCardNo = new javax.swing.JTextField();
        jTextFieldRegNo = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Αριθμός κάρτας:");
        jLabel1.setToolTipText("");

        jLabel2.setText("Αριθμός κυκλοφορίας:");

        jSpinnerFromDate.setModel(new javax.swing.SpinnerDateModel());

        jLabel3.setText("Από:");

        jSpinnerToDate.setModel(new javax.swing.SpinnerDateModel());

        jLabel4.setText("Έως:");

        jButtonSearch.setText("Αναζήτηση");
        jButtonSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSearchActionPerformed(evt);
            }
        });

        jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jButtonCancel.setText("Άκυρο");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, listHistoryCollection, jTable2, "");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cardId.id}"));
        columnBinding.setColumnName("Αριθμός κάρτας");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${passTimestamp}"));
        columnBinding.setColumnName("Χρόνος διέλευσης");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tollCollected}"));
        columnBinding.setColumnName("Ποσό πληρωμής");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane2.setViewportView(jTable2);

        jTextFieldRegNo.setToolTipText("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonSearch)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextFieldCardNo)
                            .addComponent(jTextFieldRegNo, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jSpinnerFromDate, javax.swing.GroupLayout.PREFERRED_SIZE, 100, Short.MAX_VALUE)
                            .addComponent(jSpinnerToDate))
                        .addGap(28, 28, 28))))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButtonCancel)
                .addContainerGap(441, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jSpinnerFromDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldCardNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jSpinnerToDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldRegNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButtonSearch)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                .addComponent(jButtonCancel)
                .addGap(20, 20, 20))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents
//Λειτουργία πλήκτρου αναζήτησης
    private void jButtonSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSearchActionPerformed
        // TODO add your handling code here:
     try {        
         //Διάβασμα ID κάρτας από φόρμα
            String cardIDString = jTextFieldCardNo.getText();         
         //Διάβασμα αριθμού κυκλοφορίας από φόρμα   
            String regNumber = jTextFieldRegNo.getText();
            int cardID;
            if (cardIDString.isEmpty()) {
                cardID = -1;
            } else {
                cardID = Integer.parseInt(cardIDString);
                try {
                    card = em.createNamedQuery("Card.findById", Card.class).setParameter("id", cardID)
                    .getSingleResult();
                } catch (NoResultException nr) {
                    card = null;
                }
            }
            if (regNumber.isEmpty()) {
                vehicle = null;
            } else {
                try {
                    vehicle = em.createNamedQuery("Vehicle.findByRegNumber", Vehicle.class).setParameter("regNumber", regNumber)
                    .getSingleResult();
                } catch (NoResultException nr) {
                    vehicle = null;
                }
            }
            fromDate = (Date) jSpinnerFromDate.getValue();
            toDate = (Date) jSpinnerToDate.getValue();
            
            if (regNumber.isEmpty() && cardID==-1) {
                // Αναζήτηση με παράμετρο μόνο τις ημερομηνίες
                queryHistoryCollection = em.createQuery("select c from Collection c where c.passTimestamp>=?1 and c.passTimestamp<=?2 order by c.passTimestamp desc")
                    .setParameter(1, fromDate).setParameter(2, toDate);     
            } else if (regNumber.isEmpty()) {
                // Αναζήτηση με παράμετρο τις ημερομηνίες και τον αριθμό κάρτας
                queryHistoryCollection = em.createQuery("select c from Collection c where c.cardId=:cardId and c.passTimestamp>=?1 and c.passTimestamp<=?2 order by c.passTimestamp desc")
                    .setParameter("cardId", card).setParameter(1, fromDate).setParameter(2, toDate);     
            } else if (cardID==-1) {
                // Αναζήτηση με παράμετρο τις ημερομηνίες και τον αριθμό κυκλοφορίας
                 queryHistoryCollection = em.createQuery("select c from Collection c where c.cardId=:vehicleId and c.passTimestamp>=?1 and c.passTimestamp<=?2 order by c.passTimestamp desc")
                    .setParameter("vehicleId", vehicle.getCardId()).setParameter(1, fromDate).setParameter(2, toDate);     
            } else {
                // Αναζήτηση με παράμετρο τις ημερομηνίες, τον αριθμό κάρτας και τον αριθμό κυκλοφορίας */
                 queryHistoryCollection = em.createQuery("select c from Collection c where c.cardId=:cardId and c.vehicleId=:vehicleId and c.passTimestamp>=?1 and c.passTimestamp<=?2 order by c.passTimestamp desc")
                    .setParameter("cardId", card).setParameter("vehicleId", vehicle.getCardId()).setParameter(1, fromDate).setParameter(2, toDate);
            }
            
            listHistoryCollection.clear();
            listHistoryCollection.addAll(queryHistoryCollection.getResultList());
        } catch (NumberFormatException e) {
            // τι γίνεται στην περίπτωση που το cardID δεν είναι αριθμός
        }        
    }//GEN-LAST:event_jButtonSearchActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        // TODO add your handling code here:
        em.getTransaction().rollback();
        em.getTransaction().begin();
        dispose();        
    }//GEN-LAST:event_jButtonCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(HistoryCollectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(HistoryCollectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(HistoryCollectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(HistoryCollectionForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new HistoryCollectionForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private model.Collection collection;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonSearch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSpinner jSpinnerFromDate;
    private javax.swing.JSpinner jSpinnerToDate;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextFieldCardNo;
    private javax.swing.JTextField jTextFieldRegNo;
    private java.util.List<model.Collection> listHistoryCollection;
    private javax.persistence.Query queryHistoryCollection;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    Card card;
    Vehicle vehicle;
    Date fromDate;
    Date toDate;
}
